package com.ptp.web;

import java.net.InetSocketAddress;
import com.ptp.initializer.WebSocketInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.concurrent.ImmediateEventExecutor;

/**
 * 
 * @author nnli
 *
 */
public class Websocket {

	private Channel channel;
	private final ChannelGroup channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
	private final EventLoopGroup masterGroup = new NioEventLoopGroup();
	private final EventLoopGroup slaveGroup  = new NioEventLoopGroup();
	
	public void start(InetSocketAddress address){
		
		ServerBootstrap strap = new ServerBootstrap();
		strap.group(masterGroup,slaveGroup).channel(NioServerSocketChannel.class)
		     .childHandler(new WebSocketInitializer(channelGroup))
		     .option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
		
		//服务端绑定端口
		try {
			ChannelFuture future = strap.bind(8089).sync();
//			future.addListener(new ChannelFutureListener() {
//				@Override
//				public void operationComplete(ChannelFuture future) throws Exception {
//					System.out.println("channel处理完成");
//				}
//			});
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			masterGroup.shutdownGracefully();
			slaveGroup.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) {
		new Websocket().start(null);
	}
}
